package org.southyin.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class PersonMain {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, InstantiationException {
        // 1.Class.forName("org.southyin.reflect.Person"); 有配置文件时
        // 2.Person.class; 一般用于传参
        // 3. Class cls3 = p.getClass(); 一般用于已有现成的对象
//        Class cls1 = Class.forName("org.southyin.reflect.Person");
//        Class cls2 = Person.class;
//        Person p = new Person();
//        Class cls3 = p.getClass();
//        System.out.println(cls1 == cls2);
//        System.out.println(cls2 == cls3);

        Class cls = Person.class;
        // Field[] getFields()
        // Field getField(String age)
//        Field[] fields = cls.getFields();
//        for (Field field : fields) {
//            System.out.println(field.getName());
//        }

//        Field age = cls.getField("age");
//        System.out.println(age.getGenericType());
//
//        Person obj = new Person();
//        age.set(obj,20);
//        System.out.println(obj.getAge());

        Constructor[] constructors = cls.getConstructors();
        System.out.println(constructors.length);

        Constructor constructor = cls.getConstructor();
        Person o = ((Person) constructor.newInstance());
        System.out.println(o.getName());

        Constructor constructor1 = cls.getConstructor(Integer.class,String.class);
        Person tom = ((Person) constructor1.newInstance(20, "tom"));
        System.out.println(tom.getAge());

        Method getAge = cls.getMethod("getAge");
        System.out.println(getAge.invoke(o));

        Method setAge = cls.getMethod("setAge", Integer.class);
        setAge.invoke(tom, 30);
        System.out.println(getAge.invoke(tom));
    }
}
